package example.demo.route.routerule.impl;

import example.demo.route.routerule.RouteRule;
import example.demo.route.routerule.RouteRuleParent;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.Properties;

/**
 * 通过spi获取对象，再加入到spring容器
 */
public class DefaultRouteRule extends RouteRuleParent {
    /*看来spi最好是要必备无参构造器的*/

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.printf("%d,%d\n", i & 3, i % 4);
        }
    }

    /**
     * 优化的话，就加个策略模式
     */
    @Override
    public int route(Serializable serializable) {
        int tableIdx = 0;
        if (serializable instanceof Integer) {
            Integer integer = (Integer) serializable;
            int intValue = integer.intValue();
            //   i&3 等同于 i%4 符合2的幂就行
            tableIdx = intValue % this.tableSum;
        } else if (serializable instanceof Long) {
            Long lon = (Long) serializable;
            //拆箱
            long longValue = lon.longValue();
            tableIdx = (int) (longValue % this.tableSum);
        } else if (serializable instanceof String) {
            String string = (String) serializable;
            int parseInt = Integer.parseInt(string);
            tableIdx = parseInt % this.tableSum;
        }
        return tableIdx;
    }

    @Override
    public void setProperties(Properties properties) {

    }

}
